package me.shiqiang.im.run;

import me.shiqiang.im.enums.MessageCmd;
import me.shiqiang.im.listeners.RouterServerListener;
import me.shiqiang.im.msg.Login;
import me.shiqiang.im.service.RouterServerNodeClient;
import io.socket.client.IO;
import io.socket.client.Socket;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by maliangxue on 2018/4/16.
 */
@Component
public class Start implements CommandLineRunner {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    RouterServerNodeClient client;


    @Autowired
    Map<String, RouterServerListener> routerServerListeners;


    @Value("${machineId}")
    private String machineId;

    @Value("${server.id}")
    private String serverId;

    @Override
    public void run(String... strings) throws Exception {
        Collection<String> addresses=client.getAllRouterIps();
        Map<String,Socket> socketMap=new HashMap<>();
        for(String address:addresses){
            address=address.replaceAll("_","\\.").replaceAll("@",":");
            logger.info("开始连接服务器routerServier:{}", address);
            Socket socket = IO.socket(String.format("http://%s/", address));
            final String finalAddress = address;
            socket.on(Socket.EVENT_CONNECT, (args) -> {   //注册为处理程序
                System.out.println("connected!");
                logger.info("已连接服务器routerServier:{}", finalAddress);
                Login login = new Login();
                login.setProcessor(true);
                login.setUserId(Long.parseLong(serverId));
                login.setPwd(machineId);
                Object obj = JSONObject.wrap(login);
                socket.emit(MessageCmd.LOGIN, obj);
            });
            socket.on(Socket.EVENT_DISCONNECT, (args) -> System.out.println("disconnected!"));
            routerServerListeners.values().forEach(emitListener -> {
                emitListener.setSocket(socket);
                socket.on(emitListener.eventName(), emitListener);
            });
            logger.info("machineId={}", machineId);
            socket.connect();
            socketMap.put(address,socket);
        }
    }
}
